import json
# 作业归属人
import os
import time
import zipfile
import random

#脚本功能适用于 调度DM_DM的调度任务，暂时实现调度单个节点
#调度时间适用每天定时调度

owner = 'yangzhipeng'
#作业归属目录
directory = '/PRD/PRD_DM/YNFD/DM_TO_DM'
#开始时间
start_time = time.strftime('%Y-%m-%dT%H:%M:%S+08')
#连接名
connectionName='dws'
#连接ID
connectionID='b091043d8a6c46a5b07140d20ea23243'
#数据库
database='dm_prd'


#在原有时间上，加上15分钟，参数为 分，时,返回分，时，两个参数
def add_time(hour, minutes):
    minutes +=15
    if minutes >= 60:
        hour += 1
        minutes %= 60
    return hour, minutes


with open(r"input.csv",'r',encoding= 'utf8') as f1:
    line = f1.readline()
    while line != '':
        strs = line.replace("\n","").split(",")
        #调度 作业名
        task_name = strs[0]
        #节点名称，脚本名或者CDM名
        scriptName = strs[1]
        # 依赖的作业
        dependsJob = strs[2]
        #依赖的作业时间
        hour = int(strs[4])
        minute = int(strs[3])
        second = 0
        #在依赖时间之上加一段时间
        hour, minute = add_time(hour, minute)

        with open(f"job_directory/{task_name}.job", "w",encoding='utf8') as out:
            with open("template.job", "r") as f:
                jsonobj = json.load(f)
                jsonobj['basicConfig']['owner'] = owner
                jsonobj['directory'] = directory
                jsonobj['name'] = task_name
                node = jsonobj['nodes'][0]
                node['name'] = scriptName
                properties = node['properties']
                #脚本名
                properties[0]['value']=scriptName
                #连接名
                properties[1]['value']=connectionName
                #连接ID
                properties[2]['value']=connectionID

                #依赖作业
                jobs = jsonobj['schedule']['cron']['dependJobs']['jobs']
                sameWorkSpaceJobs=jsonobj['schedule']['cron']['dependJobs']['sameWorkSpaceJobs']

                jobs.append(dependsJob)
                sameWorkSpaceJobs.append({"dependOnLastPeriod":False,"jobName":dependsJob})
                #调度时间
                jsonobj['schedule']['cron']['expression'] = f"{second} {minute} {hour} * * ?"
                jsonobj['schedule']['cron']['startTime'] = start_time


                json.dump(jsonobj, out,indent=2, ensure_ascii=False)

        line = f1.readline()



with zipfile.ZipFile("job.zip",'w',zipfile.ZIP_DEFLATED) as zip:
    files = os.listdir("job_directory")
    for f in files:
        zip.write("job_directory/"+f,os.path.relpath("job_directory/"+f, "job_directory"))
    # 删除目录下的所有文件
    for f in os.listdir("job_directory"):
        os.remove("job_directory/"+f)